import { get_gun, clear_gun } from 'base/api';
import { put_log } from 'base/ctl/log';
import { g_db } from 'db/state';
import { do_event } from './event';
import { init_info } from 'use/info';
import { uJob, obj_int, cline, obj_str } from 'sui';
import { ck_box } from './box';

const do_inbox = (stepnum, step, umd, watch) => {
    const box_sn = get_gun(step);
    if (!box_sn) {
        watch.startWatch();
        return;
    }

    clear_gun();

    umd.mset({
        "box": box_sn,
        "err": "",
    });

    put_log("编码", box_sn, "扫描箱子编码");

    const herr = (e) => {
        umd.setErr(e);
        watch.startWatch();
    };

    const e = ck_box(box_sn);
    if (e) {
        return herr(e);
    }

    uJob(null, "goods/addbox",
        {
            line: cline(),
            k: box_sn,
        },
        r => {
            let attr = null;
            const box = [];

            r.forEach(d => {
                if (d.sn === "attr") {
                    attr = d;
                    return;
                }

                box.push(d);
            });

            init_info(box);

            const c = box.length;
            const task_sn = obj_str(attr, "task");

            umd.mset({
                "sum": c,
                "task": task_sn,
            });

            g_db.s_sum(c);
            g_db.s_box(box_sn);
            g_db.s_task(task_sn);
            g_db.s_boxtray(obj_int(attr, "tray"));
            g_db.s_boxlv(obj_int(attr, "level"));
            g_db.s_seal(obj_str(attr, "seal"));
            g_db.s_lub(obj_str(attr, "lub"));

            do_event("step_over", umd, watch);
        },
        e => herr("添加料箱出错"));
};

export {do_inbox};
